Django 和 Graphene:如何处理与多态模型的双向关系?答案

您所在的位置:网站首页 django union查询 Django 和 Graphene:如何处理与多态模型的双向关系?答案

Django 和 Graphene:如何处理与多态模型的双向关系?答案

2023-04-08 12:34| 来源: 网络整理| 查看: 265

我有一个看起来像这样的 Django 模型(当然是简化的):

from django.db import models from polymorphic.models import PolymorphicModel class Tournament(models.Model): slug = models.CharField(max_length=100, unique=True) class Event(PolymorphicModel): tournament = models.ForeignKey(Tournament, related_name='events') slug = models.CharField(max_length=100) class PracticeEvent(Event): pass class MatchEvent(Event): winner = models.CharField(max_length=100, null=True, blank=True, default=None)

锦标赛包括两种活动:练习活动和比赛。我想使用 GraphQL,使用 Graphene 来公开这个模型。这是我想出的:

import graphene from graphene_django import DjangoObjectType from . import models class TournamentType(DjangoObjectType): class Meta: model = models.Tournament exclude_fields = ('id',) class EventType(graphene.Interface): tournament = graphene.Field(TournamentType, required=True) slug = graphene.String(required=True) class PracticeEventType(DjangoObjectType): class Meta: model = models.PracticeEvent interfaces = (EventType,) exclude_fields = ('id',) class MatchEventType(DjangoObjectType): class Meta: model = models.MatchEvent interfaces = (EventType,) exclude_fields = ('id',) extra_types = {PracticeEventType, MatchEventType} class Query(graphene.ObjectType): tournaments = graphene.List(TournamentType) events = graphene.List(EventType) # ... resolvers ... schema = graphene.Schema( query=Query, types=schema_joust.extra_types,)

到目前为止,一切都很好;我可以直接查询events { ... },甚至tournament也可以。但是,由于没有DjangoObjectType 和model = models.Event,我无法查询tournaments { events {...} }...

我该如何解决这个问题?我无法将EventType 设为DjangoObjectTpe,我也不知道事后添加events 字段。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3